<?php
namespace App\Models;

use App\Models\Scope\NeighborCouncilSurveyScope;
use Illuminate\Support\Facades\DB;

class NeighborCouncilSurvey extends CommonModel {
	protected $table = 'neighbor_council_survey';
	
	public static function boot()
	{
		parent::boot();
		static::addGlobalScope(new NeighborCouncilSurveyScope());
	}
	
	public function detail($uid){
		$id = $this->getAttribute('id');
		$question = $this->question()->get()->each(function($v,$k) use ($id){
			$answer = collect([]);
			$options = collect(json_decode($v->options,true))->each(function($v2,$k2) use ($id,$v,&$answer){
				$answer->push(NeighborCouncilSurveyAnswer::where(['survey_id'=>$id,'question_id'=>$v->id,'options_id'=>$k2])->count());
			});
			$v->setAttribute('options',$options);
			$v->setAttribute('answer',$answer);
		});
		$this->setAttribute('question',$question);
		// 我是否回答过
		$exists = NeighborCouncilSurveyAnswer::where(['uid'=>$uid,'survey_id'=>$id])->exists();
		$this->setAttribute('answered',$exists ? 1 : 0);
		// 回答人数
		$count = NeighborCouncilSurveyAnswer::where(['survey_id'=>$id])->groupBy('uid')->pluck('id')->count();
		$this->setAttribute('answered_count',$count);
		return $this;
	}
	
	// 只查找物业调查
	public function scopeWuye($query){
		$query->where(['type'=>0]);
	}
	
	// 只查找业委调查
	public function scopeYewei($query){
		$query->where(['type'=>0]);
	}
	
	public function question(){
		return $this->hasMany('\App\Models\NeighborCouncilSurveyQuestion','survey_id','id');
	}
}